from django.shortcuts import render
from recommend.models import SortsModel,GoodsModel
from rest_framework.views import APIView
from rest_framework.response import Response
from tools.myredis import r
import json,time
import threading
# Create your views here.


class GoodsListView(APIView):
    def get(self,request):
        res1 =r.get_str("goodslist")
        if res1:
            print('有缓存')
            return Response(res1)


        if r.get_str("goodslistlock") is None:
            print('无锁')
            r.setnx_str("goodslistlock","1")
            data = SortsModel.objects.all().values('id','name','pid')
            data = list(data)
            data_dict = {i['id']:i for i in data}
            data_list = []
            for i in data:
                if i['pid'] == None or i['pid'] == '':
                    data_list.append(i)
                else:
                    if 'children' not in data_dict[i['pid']]:
                        data_dict[i['pid']]['children'] = []
                        data_dict[i['pid']]['children'].append(i)
                    else:
                        data_dict[i['pid']]['children'].append(i)
            res = json.dumps(data_list)
            r.set_str("goodslist",res)
            r.str_del("goodslistlock")
        else:
            time.sleep(2)
            res = r.get_str("goodslist")



        return Response(res)


class GoodsCategoryListView(APIView):
    def get(self,request):
        c_id = self.request.query_params.get('c_id')

        res = r.get_str("goodscategory" + c_id)
        if res:
            print('有缓存')
            return Response(res)

        if r.setnx_str("goodscategorylock"+c_id,"1"):
            print('无锁')
            c_name = SortsModel.objects.get(id=c_id).name
            goods = list(GoodsModel.objects.filter(pid_id=c_id).values('id', 'name', 'price','store'))
            for i in goods:
                i['price'] = float(i['price'])

            with r.pipeline() as pipe:
                pipe.multi()
                for i in goods:
                    print(i)
                    pipe.set('goodsdetail'+str(i['id']),json.dumps(i))
                pipe.execute()
            res = json.dumps({'c_name':c_name,'goods':goods})
            r.set_str("goodscategory"+c_id,res)
            r.str_del("goodscategorylock"+c_id)
            return Response(res)


        else:
            time.sleep(2)
            res = r.get_str("goodscategory" + c_id)

        return Response(res)


lock = threading.Lock()

def getcart(user_id):
    cart = r.hash_getall("cart"+str(user_id))
    total = 0
    cart_data = []
    for k, v in cart.items():
        k = k.decode()
        v = json.loads(v.decode('utf-8'))
        data = json.loads(r.get_str("goodsdetail" + str(k)))
        del data['store']
        data['count'] = v['count']
        data['check_status'] = v['check_status']
        cart_data.append(data)
        if v['check_status'] == "1":
            total += (data['price'] * v['count'])
    return (cart_data, total)





class AddCartListView(APIView):

    def post(self,request):
        user_id= request.data.get('user_id')
        goods_id = request.data.get('goods_id')

        if lock.acquire(timeout=3,blocking=True):
            good = GoodsModel.objects.get(id=goods_id)
            data = r.hash_getone("cart"+str(user_id),goods_id)
            if data is None:
                if good.lockstore >= good.store:
                    lock.release()
                    return Response({'code':10001,'msg':'库存不足'})
                r.hash_add("cart"+str(user_id),goods_id,json.dumps({'count':1,'check_status':"1"}))
            else:
                data = json.loads(data)
                if data['count'] + 1 + good.lockstore > good.store:
                    lock.release()
                    return Response({'code':10001,'msg':'库存不足'})
                data['count'] += 1
                r.str_del('goodscategory' + str(good.pid_id))
                r.hash_add("cart"+str(user_id),goods_id,json.dumps(data))
            lock.release()
            return Response({'code':10000,'msg':'添加成功'})


    def get(self,request):
        user_id = request.query_params.get('user_id')
        cart_data, total = getcart(user_id)
        return Response({'cart':cart_data,'total':total})


class CheckCartView(APIView):

    def post(self,request):
        user_id = request.data.get('user_id')
        goods_id = request.data.get('goods_id')
        check_status = request.data.get('check_status')
        data = json.loads(r.hash_getone("cart"+str(user_id),goods_id))
        data['check_status'] = check_status
        r.hash_add("cart"+str(user_id),goods_id,json.dumps(data))
        return Response({'msg':'ok'})















